#!/bin/bash

set -e
cd ~/

echo "===== Step 1: 安装 OrbbecSDK_v1.10.18_arm64.deb ====="
sudo dpkg -i OrbbecSDK_v1.10.18_arm64.deb || sudo apt-get install -f -y

echo "===== Step 2: 安装 pyorbbecsdk Python 包 ====="
python3.10 -m pip install ./pyorbbecsdk-2.0.13-cp310-cp310-linux_aarch64.whl

echo "===== Step 3: 进入 pyorbbecsdk 示例目录 ====="
cd ~/.local/lib/python3.10/site-packages/pyorbbecsdk/examples || {
    echo "示例目录未找到！请确认 pyorbbecsdk 是否正确安装。" && exit 1
}

echo "===== Step 4: 安装 requirements.txt 中的依赖 ====="
python3.10 -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple

echo "===== Step 5: 安装其他依赖包 simplejpeg, flask, scipy ====="
python3.10 -m pip install simplejpeg flask scipy -i https://mirrors.aliyun.com/pypi/simple

echo "===== Step 6: 添加当前用户到 input 用户组 ====="
sudo usermod -aG input $USER

echo "===== Step 7: 添加当前用户到 video 和 plugdev 组（推荐） ====="
sudo usermod -aG video $USER
sudo usermod -aG plugdev $USER

echo "===== Step 8: 重新加载 udev 规则并触发设备检测 ====="
sudo udevadm control --reload-rules
sudo udevadm trigger

echo "===== 使用中国科技大学 apt 源 ====="
sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak
sudo bash -c 'cat > /etc/apt/sources.list <<EOF
deb https://mirrors.ustc.edu.cn/ubuntu/ $(lsb_release -sc) main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ $(lsb_release -sc)-updates main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ $(lsb_release -sc)-backports main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ $(lsb_release -sc)-security main restricted universe multiverse
EOF'

sudo apt-get update

echo "===== 所有步骤完成，建议现在重启系统 ====="
read -p "是否现在重启系统？(y/n): " confirm
if [[ "$confirm" == "y" || "$confirm" == "Y" ]]; then
    sudo reboot
else
    echo "请手动重启以完成设置。"
fi
